﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using HySoft.Cash.BaseClass;
using System.Configuration;
using HySoft.Cash.Business;
using HySoft.Cash.Structure;
using PayRoller.Code;
using System.Data;
using HySoft.Cash;

namespace PayRoller.Include
{
    public partial class UInvoiceDetail : System.Web.UI.UserControl
    {
        // Fields
        protected Literal litInvoiceAmount;
        public DataTable dtEmpList = new DataTable();
        //public DataTable dtOpeningInvoices = new DataTable();
        public double fCreditAvailable;
        public double fCreditBalance;
        public double fCreditLimit;
        public double fClosingBalance;
        public double fDailyRate;
        public double fInterestCharges;
        protected HtmlForm form1;
        public double fPenalty;
        public double fCurrentTotal;
        public double fSumAmount;
        public double fSumFinanceCost;
        public double fSumNetPay;
        public double fTotalDue;
        protected HtmlHead Head1;
        public int iEmialDueDate;
        public int iInvoiceDueDate;
        public int OrgSid;
        public string sContactPerson = "";
        public string sInvoiceAmount = "";
        public string sInvoiceDate = "";
        public string sInvoiceSid = "";
        public string sInvoiceToDate = "";
        public string sOrgName = "";
        public string sPaymentDate = "";
        public string sPostalAddress = "";
        public Guid invoiceGUID = Guid.Empty;
        public int invoiceID = 0;
        protected HtmlImage picLogo;
        public double fPreviousBalance;
        public double fPaidFromPreviousBalance;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (((base.Request["Guid"] != null)) && (base.Request["Guid"].ToString() != ""))
            {
                this.iInvoiceDueDate = Convert.ToInt32(this.GetSysOptionValue(2));
                this.iEmialDueDate = Convert.ToInt32(this.GetSysOptionValue(3));
                this.fDailyRate = Convert.ToDouble(this.GetSysOptionValue(5));
                this.invoiceGUID = new Guid(base.Request["Guid"].ToString());
                this.sInvoiceSid = this.GetInvoiceSidByGuid(base.Request["Guid"].ToString());
                this.invoiceID = Convert.ToInt32(this.sInvoiceSid);
                if (base.Request["OrgSid"] == null)
                {
                    this.OrgSid = GetOrgIDByGuid(base.Request["OrgSid"]);
                }
                else
                {
                    this.OrgSid = Convert.ToInt32(base.Request["OrgSid"]);
                }

                this.GetOrgInfo(this.OrgSid);
                this.GetInvoiceInfo(this.invoiceID);
                //this.dtOpeningInvoices= this.GetOpeningInvoices(this.invoiceID, this.OrgSid);
                this.fCreditAvailable = this.fCreditLimit - this.fCreditBalance;
                
                this.dtEmpList = this.GetEmpList();
                //this.fSumFinanceCost = this.GetSumFinanceCost(this.dtEmpList);
                
                this.fSumAmount = this.GetSumAount(this.dtEmpList);
                this.fTotalDue = fSumAmount + fPenalty + fInterestCharges;//((this.fClosingBalance + this.fSumFinanceCost) + this.fPenalty) + this.fInterestCharges;
            }

            this.picLogo.Src = "~/images/logo.jpg";
        }


        public double GetEmpAmount(int EmpSid)
        {
            double num = 0.0;
            double num2 = 0.0;
            TemppaymentBN tbn = new TemppaymentBN(this.Page);
            tbn.QueryEmpSid(EmpSid);
            DataTable list = tbn.GetList();
            for (int i = 0; i < list.Rows.Count; i++)
            {
                num2 = Convert.ToDouble(list.Rows[i]["PaymentAmount"]);
                num += num2;
            }
            tbn.Close();
            tbn.Dispose();
            return num;
        }

        public DataTable GetEmpList()
        {
            SqlParameter[] commandParameters = new SqlParameter[] { new SqlParameter("@InvoiceID", this.invoiceGUID) };
            return SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["SQLConnString"], CommandType.StoredProcedure, "GetInvoiceEmpInfo", commandParameters).Tables[0];
        }

        /// <summary>
        /// 获取当前用户尚未关闭且早于当前Invoice的Invoice列表
        /// </summary>
        /// <returns></returns>
        public DataTable GetOpeningInvoices(int currentInvoiceID,int currentOrgID)
        {
            string sql = string.Format("select (Principal + Interest+ PenaltyPaid + LateInterestChargesPaid) as InvoiceAmount,(PrincipalPaid + InterestPaid + PenaltyPaid + LateInterestChargesPaid) as  ReceiveAmount from [tInvoiceList] where sid<{0} and OrgSid={1} and (IsValid={2}  or IsValid={3}) ", currentInvoiceID, currentOrgID,(int)InvoiceStatuses.InitStatus, (int)InvoiceStatuses.Overdue);
            return SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["SQLConnString"],CommandType.Text,sql).Tables[0];
        }

        public void GetInvoiceInfo(int Sid)
        {
            using (TinvoicelistBN tbn = new TinvoicelistBN(this.Page))
            {
                TinvoicelistDT tdt = tbn.Get(Sid);
                this.sInvoiceDate = Convert.ToDateTime(tdt.InvoiceDate).ToString(AppSettings.DateFormatAU);
                this.sPaymentDate = Convert.ToDateTime(tdt.PaymentDate).ToString(AppSettings.DateFormatAU);
                this.sInvoiceAmount = tdt.InvoiceAmount.ToString();
                this.fPenalty = Convert.ToDouble(tdt.Penalty);
                this.fInterestCharges = Convert.ToDouble(tdt.LateInterestCharges);
                int invoiceOverDueDays = AppSettings.InvoiceOverDueDays;
                this.fClosingBalance = Convert.ToDouble(tdt.LastFeeBalance);
                this.fCreditBalance = Convert.ToDouble(tdt.LastCreditBalance);
                this.sInvoiceToDate = Convert.ToDateTime(tdt.InvoiceDate).AddDays(invoiceOverDueDays).ToString(AppSettings.DateFormatAU);

                this.fPreviousBalance= Convert.ToDouble(tdt.PreviousBalance);
                this.fPaidFromPreviousBalance= Convert.ToDouble(tdt.PaidFromPreviousBalance);
                tbn.Close();
                tbn.Dispose();
            }
        }

        public int GetOrgIDByGuid(string Guid)
        {
            using (TinvoicelistBN tbn = new TinvoicelistBN(this.Page))
            {
                tbn.QueryGuid(Guid);
                DataTable list = tbn.GetList();
                tbn.Close();
                tbn.Dispose();
                if (list.Rows.Count > 0)
                {
                    return Convert.ToInt32(list.Rows[0]["OrgSid"]);
                }
                return 0;
            }
        }

        public string GetInvoiceSidByGuid(string Guid)
        {
            using (TinvoicelistBN tbn = new TinvoicelistBN(this.Page))
            {
                tbn.QueryGuid(Guid);
                DataTable list = tbn.GetList();
                tbn.Close();
                tbn.Dispose();
                if (list.Rows.Count > 0)
                {
                    return list.Rows[0]["Sid"].ToString();
                }
                return ""; 
            }
        }

        public void GetOrgInfo(int OrgSid)
        {
            using (TorginfoBN obn = new TorginfoBN(this.Page))
            {
                TorginfoDT odt = obn.Get(OrgSid);
                this.sOrgName = odt.OrgName;
                this.sContactPerson = odt.ContactPerson;
                this.sPostalAddress = odt.PostalAddress;
                this.fCreditLimit = Convert.ToDouble(odt.CreditLimit);
                obn.Close();
                obn.Dispose(); 
            }
        }

        public double GetSumFinanceCost(DataTable dt)
        {
            double num = 0.0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                double num4 = ((Convert.ToDouble(dt.Rows[i]["Amount"]) * 0.01) * this.fDailyRate) * this.iInvoiceDueDate;
                num += num4;
            }
            return num;
        }

        public double GetSumAount(DataTable dt)
        {
            double sumAcount = 0.0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                double singleAmount = Convert.ToDouble(dt.Rows[i]["Amount"]);
                double num4 = ((singleAmount * 0.01) * this.fDailyRate) * this.iInvoiceDueDate+ singleAmount;
                sumAcount += num4;
            }
            return sumAcount;
        }

        public string GetSysOptionValue(int Sid)
        {
            using (TsysoptionBN nbn = new TsysoptionBN(this.Page))
            {
                TsysoptionDT ndt = nbn.Get(Sid);
                nbn.Close();
                nbn.Dispose();
                if (ndt != null)
                {
                    return ndt.OptionValue;
                }
                return ""; 
            }
        }
    }
}